package com.ce.server.config.security;

import com.ce.server.pojo.Menu;
import com.ce.server.pojo.Role;
import com.ce.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求的url返回所需要的角色
 *
 * @DATE: 2021/11/14 23:40
 * @Author: 小爽帅到拖网速
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

  @Autowired
  private IMenuService menuService;

  AntPathMatcher antPathMatcher = new AntPathMatcher();

  @Override
  public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    // 获取请求的url
    String requestUrl = ((FilterInvocation) object).getRequestUrl();
    List<Menu> menus = menuService.getMenusWithRole();
    for (Menu menu : menus) {
      // 判断请求中url跟menu中角色是否匹配   如果匹配得上就进行访问，匹配不上就返回权限不足
      if (antPathMatcher.match(menu.getUrl(),requestUrl)){
        String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
        return org.springframework.security.access.SecurityConfig.createList(str);
      }
    }
    // 没匹配的url默认登录即可访问
    return SecurityConfig.createList("ROLE_LOGIN");
  }

  @Override
  public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return false;
  }
}
